package com.example.kfcclient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.Toast;


public class expListActivity extends Activity {
	
	private ProgressDialog pDialog;
	 ArrayList<HashMap<String, String>> menuList;
	 ArrayList<HashMap<String, String>> productsList;
	private static String url_all_product = "http://khoaluankfc.freevnn.com/API/list_product.php";
	
	JSONArray product;
	JSONArray child_product;
	//JSon Node Name
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_TITLE = "title";
	private static final String TAG_PRODUCT = "product";
	private static final String TAG_CHILDPRODUCT = "child_product";
	private static final String TAG_NAME = "name";
	private static final String TAG_PRICE = "price";
	private static final String TAG_IMAGE = "image";
	private static final String TAG_ID = "id_title";
	private static final String TAG_CATEID = "id_title";
	private static final String TAG_ITEMID = "id_child";
	DisplayMetrics metric;
	int width;
	public final Context THIS = this;
	MyExpListAdapter adapter;
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.explist);
		
		new LoadProduct().execute();
		
		
		ExpandableListView list = (ExpandableListView) findViewById(R.id.list);
		list.setOnChildClickListener(new OnChildClickListener() {
			
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				return false;
			}
		});
		list.setOnGroupClickListener(new OnGroupClickListener() {
			
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				// TODO Auto-generated method stub
				return false;
			}
		});
		//fakeData();
			
		metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels;
		// đưa indicator vào thanh group row
		list.setIndicatorBounds(width-GetDipsFromPixel(50), width-GetDipsFromPixel(10));
	}
	// xác định vị trí pixel
	public int GetDipsFromPixel(float pixels)
    {
     // Get the screen's density scale
     final float scale = getResources().getDisplayMetrics().density;
     // Convert the dps to pixels, based on density scale
     return (int) (pixels * scale + 0.5f);
    }
	
	// bất đồng bô việc load dữ liệu json
	class LoadProduct extends AsyncTask<String, String, String >
	{

		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		InputStream is = null;
		String result = null;
		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pDialog = new ProgressDialog(expListActivity.this);
			pDialog.setMessage("Loading product. please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			try{
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(url_all_product);
				httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				
				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity httpEntity = httpResponse.getEntity();
				is = httpEntity.getContent();
				
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{
					sb.append(line + "\n");
				}
				is.close();
				result = sb.toString();
			}
			catch (Exception e) {
				// TODO: handle exception
				Toast.makeText(expListActivity.this, "http connect error : " + e.toString(), Toast.LENGTH_LONG).show();
			}
			return result;
		}



		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(String  result) {
			// TODO Auto-generated method stub
			pDialog.dismiss();
			Log.d("product all : ", result);
			ArrayList<Catalogy> groups = new ArrayList<Catalogy>();
			ArrayList<ArrayList<Item>> children = new ArrayList<ArrayList<Item>>();
			ArrayList<Item> itemList ;
			try{
				if(result == null)
					throw new Exception("result is null");
				JSONObject json_data = new JSONObject(result);
				
				int success = json_data.getInt(TAG_SUCCESS);
				if(success == 1)
				{
					product = json_data.getJSONArray(TAG_PRODUCT);
					for(int i=0;i<product.length();i++)
					{
						Catalogy catalogy = new Catalogy();
						JSONObject c = product.getJSONObject(i);
						String title = c.getString(TAG_TITLE);
						long id = c.getLong(TAG_ID);
						catalogy.setId(id);
						catalogy.setName(title);
						groups.add(catalogy);
						
						child_product = json_data.getJSONArray(TAG_CHILDPRODUCT);
						itemList = new ArrayList<Item>();
						for(int j=0;j<child_product.length();j++)
						{
							Item item = new Item();
							JSONObject c1 = child_product.getJSONObject(j);
							long cateID = c1.getLong(TAG_CATEID);
							long itemID = c1.getLong(TAG_ITEMID);
							String name = c1.getString(TAG_NAME);
							String image = c1.getString(TAG_IMAGE);
							int price = c1.getInt(TAG_PRICE);
							if(cateID==id)
							{
								item.setCateId(cateID);
								item.setItemId(itemID);
								item.setName(name);
								item.setIcon(image);
								item.setPrice(price);
								item.setNumberFood("1");
								item.setSelected(false);
								Log.d("name", name);
								itemList.add(item);
							}
							
						}
						children.add(itemList);
					}
					
					
					ExpandableListView list = (ExpandableListView) findViewById(R.id.list);
					adapter = new MyExpListAdapter(THIS,groups,children);
					list.setAdapter(adapter);
				}
				else
				{
					Toast.makeText(expListActivity.this, "Không có dữ liệu", Toast.LENGTH_LONG).show();
				}
			}
			catch (Exception e) {
				// TODO: handle exception
				Toast.makeText(expListActivity.this, "loi gi ko biet" + e.getMessage(), Toast.LENGTH_LONG).show();
			}
		}
		
	}
}
